import {
  login,
  getSysMemberCurrMemInfo,
  tokenOut,
  getNlQueryFsUrl
} from '@/api/management/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import store from '../../store'
import { guid } from '@/utils'
import { Notification } from 'element-ui'
import { getQueryParamValue } from '@/api/management/parameter'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: '',
    checkcodeid: '',
    baseUrl: '',
    socket: null,
    socketTime: null
  }
}

const state = getDefaultState()

const mutations = {
  // 一般用于退出重置 仓库state数据
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  setCheckcodeid: (state, checkcodeid) => {
    state.checkcodeid = checkcodeid
  },
  setBaseUrl: (state, url) => {
    state.baseUrl = url
  },
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          if (response.data.bdata) {
            console.log(response)
            commit('SET_TOKEN', response.data.bdata.token)
            setToken(response.data.bdata.token)
            resolve()
          } else {
            reject(response)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      tokenOut().then(res => {
        if (res.code == 0 && res.data.bcode == 0) {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          // 退出的时候重置缓存tab栏
          store.dispatch('tagsView/delAllViews', null, { root: true })
          resolve()
        }
      })
    })
  },

  topslogout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  getUserInfo ({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      getSysMemberCurrMemInfo()
        .then(async response => {
          if (response.data.code == 2) {
            resolve('err')
          }
          if (response.data.data.bdata) {
            commit('setUserInfo', response.data.data.bdata)
            // socketFn(state)
            resolve()
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  getBaseUrl ({ commit }) {
    return new Promise(async (resolve, reject) => {
      getNlQueryFsUrl()
        .then(async response => {
          commit('setBaseUrl', response.data.bdata)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

// 启用socket，并且获取消息，并显示徽标
async function socketFn (state) {
  // 如果存在socket，不重复链接
  if (state.socket) return
  // 如果没有开启socket，不执行
  let ifSocket = await getQueryParamValue('010202006')
  if (!ifSocket) return
  // 获取url地址
  let url = await getQueryParamValue('010202007')
  state.socket = new WebSocket(url.data.bdata);
  // 默认执行一次登录连接
  state.socket.onopen = (e) => {
    console.log("连接成功", e);

    state.socket.send(
      JSON.stringify({
        type: 0,
        data: { id: state.userInfo.member.id },
        msgId: guid(),
      })
    );
  };
  // 接收消息
  state.socket.onmessage = (event) => {
    let res = JSON.parse(event.data)
    if (res.type == 2 && res.data.bdata) {
      let bdata = JSON.parse(res.data.bdata)
      Notification.info({
        title: '消息',
        message: bdata.title
      })
    }

  };
  // 错误重连
  state.socket.onerror = () => {
    clearInterval(state.socketTime);
    console.log("连接错误");
    state.socket.close();
    state.socket = null;
    socketFn(state);
  }
  // 断开重连
  state.socket.onclose = () => {
    clearInterval(state.socketTime);
    console.log("连接关闭");
    state.socket = null;
    socketFn(state);
  }
  // 每10s通知服务器我还在线
  state.socketTime = setInterval(() => {
    state.socket.send(
      JSON.stringify({
        type: 3,
        msgId: guid(),
      })
    );
  }, 10000);
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
